<script setup>

import Card from "@/components/Card.vue";
import LightCard from "@/components/LightCard.vue";
import {
  ArrowRightBold,
  CircleCheck,
  Clock,
  CollectionTag,
  Compass,
  Document,
  Edit,
  EditPen, FolderOpened,
  Link, Microphone,
  Picture,
  Star,
  Sunny
} from "@element-plus/icons-vue";
import Weather from "@/components/Weather.vue";
import {computed, reactive, ref, watch} from "vue";
import {get} from "@/net";
import {ElMessage} from "element-plus";
import TopicEditor from "@/components/TopicEditor.vue";
import router from "@/router";
import TopicTag from "@/components/TopicTag.vue";
import topics from "quill-image-resize-vue";
import {useStore} from "@/store";
import ColorDot from "@/components/ColorDot.vue";
import TopicCollectList from "@/components/TopicCollectList.vue";

const store = useStore()

//当前日期
const today = computed(() => {
  const date = new Date()
  return `${date.getFullYear()} 年 ${date.getMonth() + 1} 月 ${date.getDate()} 日`
})

//获取位置信息数据 和 天气情况
const weather = reactive({
  location: {},
  now: {},
  hourly: [],
  success: false
})
navigator.geolocation.getCurrentPosition(position => {
  const longitude = position.coords.longitude
  const latitude = position.coords.latitude
  get(`/api/forum/weather?longitude=${longitude}&latitude=${latitude}`, data => {
    Object.assign(weather, data)
    weather.success = true
  })
}, error => {
  console.info(error)
  ElMessage.warning('位置信息获取超时，请检测网络设置')
  get(`/api/forum/weather?longitude=116.40529&latitude=39.90499`, data => {
    Object.assign(weather, data)
    weather.success = true
  })
}, {
  timeout: 10000,
  enableHighAccuracy: true
})

//富文本编辑器
const editor =ref(false)

//整理到一起
const topicsVar = reactive({
  list: [],
  type: 0,
  page: 0,
  end: false,
  top: []
})
watch(()=>topicsVar.type, () =>
  //更新类型信息时候，初始化页面列表状态信息
  resetList(), {immediate: true})

//加载置顶帖子
get('/api/forum/top-topic', data => topicsVar.top = data)

//初始化帖子列表
function updateTopicList(){
  //如果到头了，不用再加载了
  if(topicsVar.end) {
    console.log("end")
    return
  }
  get(`/api/forum/list-topic?page=${topicsVar.page}&type=${topicsVar.type}`, data => {
    if(data) {
      data.forEach(d => topicsVar.list.push(d))
      topicsVar.page++
    }
    if(!data || data.length < 10)
      topicsVar.end = true
  })
}
// updateTopicList()

//创建帖子
function onTopicCreate() {
  editor.value = false
  resetList()
}

//重置列表状态
function resetList() {
  topicsVar.page = 0
  topicsVar.end = false
  topicsVar.list = []
  updateTopicList()
}


// 使用异步请求获取 IP 地址
const ip = ref("0.0.0.0")
const ipShow = ref(false)
async function getIp(){
  try {
    const response = await fetch('https://api.ipify.org?format=json');
    const data = await response.json();
    ip.value = data.ip;
    ipShow.value = true;
    console.log(data)
  } catch (error) {
    console.log('获取 IP 地址失败:', error);
  }
}

//收藏夹栏目状态
const collects = ref(false)

</script>

<template>
  <div style="margin: 20px auto;display: flex;gap: 20px;max-width: 1100px">
<!--    帖子列表-->
    <div style="flex: 1">
<!--      发布话题-->
      <light-card>
        <div class="create-topic"
             @click="editor = true">
          <el-icon><EditPen/></el-icon>
          点击发表话题...
        </div>
        <div style="margin-top: 10px;display: flex;gap: 13px;font-size: 18px;color: grey">
          <el-icon><Edit /></el-icon>
          <el-icon><Document /></el-icon>
          <el-icon><Compass /></el-icon>
          <el-icon><Picture /></el-icon>
          <el-icon><Microphone /></el-icon>
        </div>
      </light-card>
<!--      置顶帖子-->
      <light-card style="margin-top: 10px;display: flex;flex-direction: column;gap: 10px">
        <div v-for="item in topicsVar.top"
             class="top-topic"
             @click="router.push(`/index/topic-detail/${item.id}`)">
          <el-tag type="info" size="small">置顶</el-tag>
          <div>{{item.title}}</div>
          <div>{{new Date(item.time).toLocaleDateString()}}</div>
        </div>
      </light-card>
<!--      类型选择-->
      <light-card style="margin-top: 10px;display: flex;gap: 7px">
        <div :class="`type-select-card ${topicsVar.type === item.id ? 'active' : ''}`"
             v-for="item in store.forum.types"
             @click="topicsVar.type = item.id">
          <color-dot :color="item.color"/>
          <span style="margin-left: 5px">{{item.name}}</span>
        </div>
      </light-card>
<!--        话题列表-->
      <div style="margin-top: 10px;display: flex;flex-direction: column;gap: 10px">
        <transition name="el-zoom-in-top" mode="out-in">
          <div v-if="topicsVar.list.length">
            <div style="margin-top: 10px;display: flex;flex-direction: column;gap: 10px"
                  v-infinite-scroll="updateTopicList">
              <!--设置跳转到子路由-->
              <light-card v-for="item in topicsVar.list" class="topic-card"
                          @click="router.push('/index/topic-detail/'+item.id)">
                <!--          用户信息、发表时间-->
                <div style="display: flex">
                  <div>
                    <el-avatar :size="30" :src="store.avatarUserUrl(item.avatar)"/>
                  </div>
                  <div style="margin-left: 7px;transform: translateY(-2px)">
                    <div style="font-size: 13px;font-weight: bold">{{item.username}}</div>
                    <div style="font-size: 12px;color: grey">
                      <el-icon><Clock/></el-icon>
                      <div style="margin-left: 2px;display: inline-block;transform: translateY(-2px)">
                        {{new Date(item.time).toLocaleString()}}
                      </div>
                    </div>
                  </div>
                </div>
                <!--          类型信息、标题-->
                <div style="margin-top: 5px">
                  <topic-tag :type="item.type"/>
                  <span style="font-weight: bold;margin-left: 7px">{{item.title}}</span>
                </div>
                <!--          内容概览-->
                <div class="topic-content">{{item.text}}</div>
                <!--          图片-->
                <div style="display: grid;grid-template-columns: repeat(3, 1fr);grid-gap: 10px">
                  <el-image class="topic-image" v-for="img in item.images" :src="img" fit="cover"></el-image>
                </div>
                <!--          点赞收藏-->
                <div style="display: flex;gap: 20px;font-size: 13px;margin-top: 10px;opacity: 0.8">
                  <div>
                    <el-icon style="vertical-align: middle"><CircleCheck/></el-icon> {{item.like}}点赞
                  </div>
                  <div>
                    <el-icon style="vertical-align: middle"><Star/></el-icon> {{item.collect}}收藏
                  </div>
                </div>
              </light-card>
            </div>
          </div>
        </transition>
      </div>
    </div>

<!--    其他杂项-->
    <div style="width: 280px">
      <!--    粘性布局，保持不动-->
      <div style="position: sticky;top: 20px">
        <light-card>
          <div class="collect-list-button" @click="collects = true">
            <span><el-icon><FolderOpened /></el-icon> 查看我的收藏</span>
            <el-icon style="transform: translateY(3px)"><ArrowRightBold/></el-icon>
          </div>
        </light-card>
        <light-card style="margin-top: 15px">
          <div style="font-weight: bold">
            <el-icon><CollectionTag/></el-icon>
            论坛公告
          </div>
          <el-divider style="margin: 10px"/>
          <div style="font-size: 14px;margin: 10px;color: grey;text-indent: 2em">
            <p>尊敬的NFT交流社区成员你好，很高兴您加入我们的NFT交流社区！本社区旨在推动NFT行业的发展和区块链技术的进步。</p>
            <p>现在，我们的社区已经发展壮大，拥有超过14亿名活跃会员。每天都有新的作品发布，人们积极参与讨论和互动。欢迎你加入我们的社区，共同建设一个繁荣、有趣和充满创造力的NFT交流社区！</p>
            <p>问题反馈社区管理员：alan223</p>
          </div>
        </light-card>
        <light-card style="margin-top: 10px">
          <div style="font-weight: bold">
            <el-icon><Sunny/></el-icon>
            天气信息
          </div>
          <el-divider style="margin: 10px 0"/>
          <weather :data="weather"/>
        </light-card>

        <light-card style="margin-top: 10px">
          <div class="info-text">
            <div>当前日期</div>
            <div>{{today}}</div>
          </div>
          <div class="info-text">
            <div>当前IP地址</div>
            <ElButton
                style="margin: 5px 5px;"
                type="warning" @click="getIp" v-show="!ipShow" size="small">查看当前Ip</ElButton>
            <div v-show="ipShow">{{ip}}</div>
          </div>
        </light-card>
        <div style="font-size: 14px;margin-top: 10px;color: grey">
          <el-icon><Link/></el-icon>
          友情链接
          <el-divider style="margin: 10px 0"/>
        </div>
        <div style="display: grid;grid-template-columns: repeat(2, 1fr);grid-gap: 10px;margin-top: 10px">
          <div class="friend-link">
            <el-image style="height: 100%" src="https://element-plus.org/images/js-design-banner.jpg"/>
          </div>
          <div class="friend-link">
            <el-image style="height: 100%" src="https://element-plus.org/images/vform-banner.png"/>
          </div>
          <div class="friend-link">
            <el-image style="height: 100%" src="https://element-plus.org/images/sponsors/jnpfsoft.jpg"/>
          </div>
        </div>
      </div>
    </div>
<!--    富文本编辑器-->
    <TopicEditor
        :show="editor"
        @close="editor = false"
        @success="onTopicCreate">
    </TopicEditor>
<!--    收藏夹栏-->
    <topic-collect-list :show="collects" @close="collects = false"/>
  </div>

</template>

<style lang="less" scoped>
.collect-list-button {
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  transition: .3s;

  &:hover {
    cursor: pointer;
    opacity: 0.6;
  }
}

.top-topic {
  display: flex;

  div:first-of-type {
    font-size: 14px;
    margin-left: 10px;
    font-weight: bold;
    opacity: 0.8;
    transition: color .3s;

    &:hover {
      color: grey;
    }
  }

  div:nth-of-type(2) {
    flex: 1;
    color: grey;
    font-size: 13px;
    text-align: right;
  }

  &:hover {
    cursor: pointer;
  }
}

.type-select-card {
  background-color: #f5f5f5;
  padding: 2px 7px;
  font-size: 14px;
  border-radius: 3px;
  box-sizing: border-box;
  transition: background-color .3s;

  &.active {
    border: solid 1px #ead4c4;
  }

  &:hover {
    cursor: pointer;
    background-color: #dadada;
  }
}

.topic-card {
  padding: 15px;
  transition: scale .3s;

  &:hover {
    scale: 1.015;
    cursor: pointer;
  }

  .topic-content {
    font-size: 13px;
    color: grey;
    margin: 5px 0;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .topic-image {
    width: 100%;
    height: 100%;
    max-height: 110px;
    border-radius: 5px;
  }
}

.info-text {
  display: flex;
  justify-content: space-between;
  color: grey;
  font-size: 14px;
}

.friend-link {
  border-radius: 5px;
  overflow: hidden;
}

.create-topic {
  background-color: #efefef;
  border-radius: 5px;
  height: 40px;
  color: grey;
  font-size: 14px;
  line-height: 40px;
  padding: 0 10px;

  &:hover {
    cursor: pointer;
  }
}

.dark {
  .create-topic {
    background-color: #232323;
  }

  .type-select-card {
    background-color: #282828;

    &.active {
      border: solid 1px #64594b;
    }

    &:hover {
      background-color: #5e5e5e;
    }
  }
}
</style>